﻿// Spun AJAX Framework
// Copyright (C) 2008 Blake Hegerle
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System.Collections.Generic;

namespace Formality
{
    public class Set<T> : ICollection<T>
    {
        public Set()
        {
            Model = new Dictionary<T, object>();
        }

        public Set(IEqualityComparer<T> Comparer)
        {
            Model = new Dictionary<T, object>(Comparer);
        }

        public bool TryAdd(T item)
        {
            var OldCount = Count;

            Model[item] = null;

            return OldCount != Count;
        }

        #region ICollection<T> Members
        public void Add(T item) { Model[item] = null; }
        public void Clear() { Model.Clear(); }
        public bool Contains(T item) { return Model.ContainsKey(item); }

        public void CopyTo(T[] array, int arrayIndex)
        {
            foreach (var i in this)
                array[arrayIndex++] = i;
        }

        public int Count { get { return Model.Count; } }
        public bool IsReadOnly { get { return false; } }
        public bool Remove(T item) { return Model.Remove(item); }
        #endregion

        #region IEnumerable<T> Members
        public IEnumerator<T> GetEnumerator() { return Model.Keys.GetEnumerator(); }
        #endregion

        #region IEnumerable Members
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        { return this.GetEnumerator(); }
        #endregion

        private Dictionary<T, object> Model;
    }
}
